import Imagelocation from '@/components/Imagelocation';
import rightGo from '@/images/common/rightGo.png';
import { useAutoHideLoading } from '@/utils/hooks/useAutoHideLoading';
import useEffectOnce from '@/utils/hooks/useEffectOnce';
import { useInterval } from '@/utils/hooks/useInterval';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import utils from '@/utils/index';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import './index.scss';

const height_left = utils.getSizeByScale(88);
const height_header = utils.getSizeByScale(94),
  height_oneLine = utils.getSizeByScale(190),
  height_oneLineMar = utils.getSizeByScale(24),
  height_mar = utils.getSizeByScale(8);
let timer = null;

const ShopIndustryAll = ({ dispatch, loading, appConfig, industryAll = [] }) => {
  const [curLeftToTop, setCurLeftToTop] = useState(0);
  const [curRightToTop, setCurRightToTop] = useState(0);
  const [curLeftSelect, setCurLeftSelect] = useState(0);
  const [bottomAreaH, setBottomAreaH] = useState(0);
  const eachRightItemToTop = useRef(null);
  const preventScrollHandle = useRef(false);

  // 显示数据
  const [industry, setIndustry] = useState([]);

  const [clear, runRef] = useInterval(
    (cacheRef, inputIndustry) => {
      console.log('debug for industry split show', {
        current: cacheRef.current || 0,
        next: (cacheRef.current || 0) + 5,
        total: inputIndustry,
      });

      // 服务器数据未获取, 不执行任务
      if (!inputIndustry?.length) {
        cacheRef.current = 0;
        return;
      }

      // 当前渲染个数
      cacheRef.current = (cacheRef.current || 0) + 5;

      setIndustry(
        // 将 secondIndustryResponse 在渲染个数(cacheRef.current)以内的进行渲染
        inputIndustry.slice(1).map(({ secondIndustryResponse, ...rest }, index) => {
          return {
            ...rest,
            secondIndustryResponse: index >= cacheRef.current ? [] : secondIndustryResponse,
          };
        }),
      );

      // 渲染个数完成, 清空定时器
      if (cacheRef.current >= inputIndustry.length - 1) {
        clear();
      }
    },
    // 定时器时间
    500,
    // 依赖
    [industryAll],
  );

  // 当获取到服务器数据时, 立刻执行一次渲染
  useEffectOnce(() => {
    if (industryAll?.length > 0) {
      runRef.current();
      return true;
    }
  }, [industryAll, runRef]);

  // 请求数据显示loading
  useShowLoading(loading, ['productList/getIndustry'], { delay: 1000 });

  // 每次进入, 存在数据, 显示loading
  useAutoHideLoading(1000, industryAll?.length > 0);

  const goShopIndustry = (firstIndustryId, secondIndustryId, name) => {
    let url =
      '/mainSubPack/shopIndustry/index' +
      '?firstIndustryId=' +
      firstIndustryId +
      '&secondIndustryId=' +
      secondIndustryId +
      '&name=' +
      name;
    Taro.navigateTo({
      url,
    });
  };

  const getIndustry = () => {
    dispatch({
      type: 'productList/getIndustry',
    });
  };

  useEffect(() => {
    if (industryAll.length === 0) {
      getIndustry();
    }
  }, []);

  useEffect(() => {
    if (industryAll?.length > 1 && eachRightItemToTop.current == null) {
      eachRightItemToTop.current = getEachRightItemToTop();
    }
  }, [industryAll]);

  // 获取每个右侧的 bar 到顶部的距离，用来做后面的计算。
  const getEachRightItemToTop = () => {
    const { windowHeight } = Taro.getSystemInfoSync();

    const temp = industryAll.slice(1);

    let obj = {};
    let totop = 0;
    // 右侧第一类肯定是到顶部的距离为 0
    obj[temp[0].id] = totop;
    // 循环来计算每个子类到顶部的高度
    for (let i = 0; i < temp.length; i++) {
      // let height_header = 94, height_oneLine = 190, height_oneLineMar = 24, height_mar = 8;
      let secondHeight = 0;
      if (temp[i].secondIndustryResponse && temp[i].secondIndustryResponse.length > 0) {
        let sLen = temp[i].secondIndustryResponse.length;
        if (sLen <= 3) {
          secondHeight += height_oneLine;
        } else {
          let num = Math.ceil(sLen / 3);
          secondHeight += height_oneLine * num;
          secondHeight += height_oneLineMar * (num - 1);
        }
      }
      let theItemHeight = height_header + secondHeight + height_mar;
      totop += theItemHeight;
      obj[temp[i + 1] ? temp[i + 1].id : 'last'] = totop;

      if (i + 1 === temp.length && theItemHeight <= windowHeight) {
        setBottomAreaH(windowHeight - theItemHeight + 10);
      }
    }
    return obj;
  };

  const handleMenuItem = (itemId) => {
    preventScrollHandle.current = true;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      preventScrollHandle.current = false;
    }, 500);
    setCurLeftSelect(itemId);
    setCurRightToTop(eachRightItemToTop.current[itemId]);
  };

  const handleProListScroll = (e) => {
    if (preventScrollHandle.current) {
      return;
    }
    for (let i = 0; i < industry.length; i++) {
      let pre = eachRightItemToTop.current[industry[i].id];
      let next = eachRightItemToTop.current[industry[i + 1] ? industry[i + 1].id : 'last'];
      if (e.detail.scrollTop + 2 < next && e.detail.scrollTop + 2 >= pre) {
        setCurLeftSelect(industry[i].id);
        setCurLeftToTop(height_left * i);
        break;
      }
    }
  };

  useEffect(() => {
    utils.setTitle(appConfig?.name);
  }, [appConfig?.name]);

  return (
    <>
      <View className="ShopIndustryAllPage">
        <ScrollView
          className="firstIndustryArea"
          scrollWithAnimation
          scrollY
          scrollTop={curLeftToTop}
        >
          {industry.length > 0 &&
            industry.map((item, iIdx) => {
              let isActive = false;
              if (curLeftSelect) {
                isActive = curLeftSelect === item.id;
              } else {
                isActive = iIdx === 0;
              }
              return (
                <View
                  className={classNames('menuItem', { active: isActive })}
                  onClick={() => handleMenuItem(item.id)}
                  key={'firstIndustryItem' + item.id}
                >
                  <View
                    className={classNames('tag', {
                      active: isActive,
                      customePageBackgroundStyle: isActive,
                    })}
                  ></View>
                  <View
                    className={classNames('text', { active: isActive, customePageStyle: isActive })}
                  >
                    {item.title}
                  </View>
                </View>
              );
            })}
        </ScrollView>

        <ScrollView
          className="firstIndustryDeatilArea"
          scrollWithAnimation
          scrollY
          scrollTop={curRightToTop}
          onScroll={handleProListScroll}
        >
          {industry.length > 0 &&
            industry.map((item, cgIdx) => (
              <View className="detailItem" key={'industryDetailItem' + cgIdx}>
                <View className="header">
                  <View className="left">{item.title}</View>
                  <View className="right" onClick={() => goShopIndustry(item.id, 0, item.title)}>
                    <Text className="text">去频道</Text>
                    <Image className="arrow" src={rightGo}></Image>
                  </View>
                </View>
                <View className="secondList">
                  {item.secondIndustryResponse?.length > 0 &&
                    item.secondIndustryResponse.map((second, sIdx) => (
                      <View
                        className="secondIndustry"
                        onClick={() => goShopIndustry(item.id, second.id, item.title)}
                        key={'secondIndustry_' + sIdx}
                      >
                        <Imagelocation className="sImg" src={second.url} type="secondIndustry" />
                        <Text className="text">{second.title}</Text>
                      </View>
                    ))}
                </View>
              </View>
            ))}
          {bottomAreaH > 0 && (
            <View className="bootomAreaMore" style={{ height: bottomAreaH + 'px' }}></View>
          )}
        </ScrollView>
      </View>
    </>
  );
};

export default connect(({ loading, productList, otherApi }) => ({
  loading,
  industryAll: productList.industry,
  appConfig: otherApi.appConfig,
}))(ShopIndustryAll);
